package servlet;

import entity.Booking;
import service.BookingService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/ListServlet")
public class ListServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        BookingService service=new BookingService();

        // 页面中会传参数：第几页，页面大小
        int currPage =1;
        if(request.getParameter("currPage")!=null) {
            currPage=Integer.parseInt(request.getParameter("currPage"));
        }
        int pageSize = 3;
        if(request.getParameter("pageSize")!=null) {
            pageSize=Integer.parseInt(request.getParameter("pageSize"));
        }

        String userName=request.getParameter("userName");

        List<Booking> list=service.listAll(userName,currPage,pageSize);
        // 获取总记录数
        int count = service.count();

        // 总页数
        int totalPage = count / pageSize;

        // 判断是否有余数，有就得+1
        if (count % pageSize != 0) {
            totalPage += 1;
        }

        request.setAttribute("list", list);
        request.setAttribute("currPage", currPage);
        request.setAttribute("totalPage", totalPage);
        request.setAttribute("userName", userName);

        request.getRequestDispatcher("list.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
